/***
@文件名：download_config.js
@来源：Winford.Wang|2021-12-06，17:51
@描述：下载文件
***/
import PARAME from '@/complete/param/parameterList'
import { ipcMain, dialog, shell } from 'electron'

const path = require('path')

const initDownload = function (win) {
  let downloadObj = {
    downloadPath: '', // 要下载的链接或文件
    fileName: '', // 要保存的文件名，需要带文件后缀名
    savedPath: '' // 要保存的路径
  }
  // 监听渲染进程发出的download事件
  ipcMain.on(PARAME.GETDOENLOAD_MAIN_APP, (evt, args) => {
    downloadObj.downloadPath = args.downloadPath
    downloadObj.fileName = args.fileName
    const ext = path.extname(downloadObj.fileName)
    const filters = [{ name: '全部文件', extensions: ['*'] }]
    if (ext && ext !== '.') {
      filters.unshift({
        name: '',
        extensions: [ext.match(/[a-zA-Z]+$/)[0]]
      })
    }
    // 弹出另存为弹框，用于获取保存路径
    dialog.showSaveDialog(win, {
      filters,
      defaultPath: downloadObj.fileName
    })
    .then((result) => {
      downloadObj.savedPath = result.filePath
      if (downloadObj.savedPath) {
        win.webContents.downloadURL(downloadObj.downloadPath) // 触发will-download事件
      }
    })
    .catch(() => {})
  })
  // 开始下载
  win.webContents.session.on('will-download', (event, item) => {
    // 设置文件存放位置
    item.setSavePath(downloadObj.savedPath)
    // 下载状态
    item.on('updated', (event, state) => {
      if (state === 'interrupted') {
        console.log('下载中断，但可以恢复')
      }
      else if (state === 'progressing') {
        if (item.isPaused()) {
          console.log('暂停下载')
        }
        else {
          console.log(`Received bytes: ${item.getReceivedBytes()}`)
        }
      }
    })
    // 当下载处于终止态时触发。 包括下载完成，取消下载
    item.once('done', (event, state) => {
      if (state === 'completed') {
        shell.showItemInFolder(downloadObj.savedPath) // 下载成功后打开文件所在文件夹
      }
      else {
        console.log(`下载失败: ${state}`)
      }
      resetDownloadObj()
    })
  })
  // 重置下载路径
  function resetDownloadObj() {
    downloadObj = {
      downloadPath: '',
      fileName: '',
      savedPath: ''
    }
  }
}

export {initDownload}
